package com.miki.sirius.demo.interceptor.config;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.miki.sirius.demo.interceptor.util.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;

/**
 * @author Surging
 * @version 1.0
 * @ClassName IPInterceptor
 * @date 2021/12/29 11:14
 * @desc IP拦截器规则定义
 */
@Slf4j
public class IPInterceptor implements HandlerInterceptor {

    //IP白名单
    public static final List<String> IPWhiteList;

    static {
        IPWhiteList = Lists.newArrayList("127.0.0.1", "172.17.0.1", "192.168.10.12");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("HelloInterceptor.preHandle  >>>>>>>>3");
        //过滤ip,若用户在白名单内，则放行
        String ipAddress = IPUtils.getRealIP(request);
        String clientIp =  request.getRemoteAddr();
        log.info("USER IP ADDRESS IS =>" + ipAddress);
        log.info("CLIENT IP ADDRESS IS =>" + clientIp);
        if (StringUtils.isEmpty(ipAddress)||!IPWhiteList.contains(ipAddress)) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            printJson(out, BaseResponse.buildFailed(ErrorCode.ERROR_CODE_513.getCode(),ErrorCode.ERROR_CODE_513.getMessage()));
            return false;
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("HelloInterceptor.preHandle  >>>>>>>>2");
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("HelloInterceptor.preHandle  >>>>>>>>1");
    }

    public void printJson(PrintWriter out, BaseResponse baseResponse){
        log.info("认证失败,返回错误信息：【{}】", JSONObject.toJSONString(baseResponse));
        out.write(JSONObject.toJSONString(baseResponse));
        out.flush();
        out.close();
    }
}

